//
//  WeatherViewController.m
//  Quick_News
//
//  Created by 曾凯峻 on 15/1/29.
//  Copyright (c) 2015年 zkj. All rights reserved.
//

#import "WeatherViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import <CoreLocation/CoreLocation.h>
#import "CityListViewController.h"
@interface WeatherViewController ()<CLLocationManagerDelegate>
@property (nonatomic,retain)NSMutableArray *arr;
@property (nonatomic,retain)NSMutableDictionary *dic;
@property (nonatomic, retain) NSString *str;

@property (nonatomic,retain)UILabel *Local;
@property (nonatomic,retain)UILabel *tmax;
@property (nonatomic,retain)UILabel *tmix;
@property (nonatomic,retain)UILabel *temp;
@property (nonatomic,retain)UILabel *prompt;
@property (nonatomic,retain)UIImageView *backPhoto;
@property (nonatomic,retain)UILabel *weatherLabel;
@property (nonatomic,retain)UIImageView *weatherPhoto;
@property (nonatomic,retain)UILabel *nowLocation;

//定位3个属性
@property (nonatomic, retain) CLLocationManager *locationManager;
@property (nonatomic, retain) CLLocation *currLocation;
@property (nonatomic, retain) CLPlacemark *placemark;

@property (nonatomic,retain)NSString *strLocation;

@end

@implementation WeatherViewController
- (void)dealloc
{
    [self.nowLocation release];
    [self.strLocation release];
    [self.locationManager release];
    [self.currLocation release];
    [self.placemark release];
    [self.weatherPhoto release];
    [self.weatherLabel release];
    [self.backPhoto release];
    [self.prompt release];
    [self.Local release];
    [self.tmax release];
    [self.tmix release];
    [self.temp release];
    [self.str release];
    [self.arr release];
    [self.dic release];
    [self.weather release];
    [self.province release];
    [super dealloc];
}



- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationController.navigationBar.translucent = NO;

     [self startLocation];
     [self createView];
 
    
    
    self.title = @"天气";
    
    //设置背景颜色
    self.view.backgroundColor = [UIColor whiteColor];
    
    //  设置导航栏左边返回按钮
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-fanhui.png"] style:UIBarButtonItemStyleDone target:self action:@selector(barButtonAction1:)]autorelease];
    
    
    
    //设置右边的导航栏
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]initWithTitle:@"[更换]" style:UIBarButtonItemStylePlain target:self action:@selector(barButtonAction:)]autorelease];
    
    
    
    //设置导航栏图片颜色
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];

    
}

- (void)startLocation
{
    self.locationManager = [[CLLocationManager alloc]init];
    // 设置定位精度
    self.locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
    self.locationManager.delegate = self;
    // 开始实时定位
    [self.locationManager startUpdatingLocation];
    // 始终允许访问
    [_locationManager requestAlwaysAuthorization];
    [_locationManager release];
    

    
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    self.currLocation = [locations lastObject];
    NSLog(@"经度 = %f 纬度 = %f", self.currLocation.coordinate.latitude, self.currLocation.coordinate.longitude);
    // 位置反编码
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:self.currLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error||placemarks.count==0) {
            NSLog(@"你的地址 没找到");
            NSLog(@"%@", error);
            
            UIAlertView *alertView  = [[UIAlertView alloc]initWithTitle:@"提示" message:@"抱歉,由于网络原因定位失败,请手动更换您所需要的城市" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
//            alertView.tag = 1111;
            [alertView show];
            [alertView release];
            
        }else {
            self.placemark=[placemarks firstObject];
            self.strLocation = self.placemark.locality;
            self.strLocation = [self.strLocation stringByReplacingOccurrencesOfString:@"市" withString:@""];
            
            if (self.strLocation) {
                self.str = self.strLocation;
                NSLog(@"所在市: %@",self.strLocation);
                
                
                
                //本地存储
                NSString *cityName = self.strLocation;
                
                //快速获取Document文件夹  在mac下也可以用
                //参数1.要获取的文件夹路径
                //参数2.在哪个问价系统获取路径 NSUserDomainMask IOS开发中只能使用这个
                //参数3.要获取的是相对路径/绝对路径(全部路径)
                NSArray *pathes =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                NSLog(@"%@",pathes);
                
                NSString *docPath = [pathes lastObject];//在数组里取一个元素
                
                NSString *strPath = [docPath stringByAppendingString:@"/city.text"];
                //简单对象写入本地2:写入路径
                //参数1:要写入的文件路径
                //参数2:是否保护当前正在写入的文件
                //参数3:指定编码格式
                //参数4:错误信息
                NSError *error = nil;
                [cityName writeToFile:strPath atomically:YES encoding:NSUTF8StringEncoding error:&error];
                
                NSLog(@"本地存储地址%@",strPath);
               
                [self creatData];
                
            }
            
        }
    }];
    [self.locationManager stopUpdatingLocation];
    [geocoder release];
    
}


- (void)creatData
{
    // 数组初始化
    self.arr = [NSMutableArray array];
    
    
    // 网络请求
    
    // 创建AFHTTPRequestOperationManager对象
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    // 手动设置设置相应内容类型(@"application/json", @"text/json", @"text/javascript"@"text/html")
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    
    NSString *str = [NSString stringWithFormat:@"http://iphone.myzaker.com/zaker/get_weather.php?city=%@",self.str];
    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSMutableDictionary *dic1 = [responseObject objectForKey:@"data"];
        NSMutableDictionary *dic2 = [dic1 objectForKey:@"datas"];
        
        //        NSLog(@"解析出来的值: %@",responseObject);
        self.weather = [[Weather alloc]init];
        
        [self.weather setValuesForKeysWithDictionary:dic2];
        [self.weather release];

        [self freshData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error:%@", error);
    }];
    
}

- (void)barButtonAction:(UIBarButtonItem *)button
{
    CityListViewController *city = [[[CityListViewController alloc] init] autorelease];
    [self.navigationController pushViewController:city animated:YES];
   
//使用block将选中的市传回来
    __block WeatherViewController *weather = self;
    [city setChangeCityBlock:^(NSString *str) {
        self.str = str;
        [weather creatData];
    }];

}

- (void)barButtonAction1:(UIBarButtonItem *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

//当点击更换城市按钮 您所在城市label就隐藏
- (void)viewDidDisappear:(BOOL)animated
{
    if (animated) {
        self.nowLocation.hidden = YES;
    }
}


- (void)createView
{

    
// 背景图片
    //背景图片
    UIImageView *bgImg=[[UIImageView alloc]initWithFrame:self.view.bounds];

    [bgImg setContentMode:UIViewContentModeScaleAspectFill];
    bgImg.autoresizesSubviews=YES;
    bgImg.opaque=YES;
    bgImg.clearsContextBeforeDrawing=YES;
    [bgImg setImage:[UIImage imageNamed:@"bac1.jpg"]];
    [self.view addSubview:bgImg];
    [bgImg release];

    
    //设置地区
    self.Local = [[UILabel alloc]init];
    _Local.frame = CGRectMake(10 , 10, self.view.frame.size.width * 1/3 + 10, self.view.frame.size.height *1/3 *1/5);
    _Local.text = self.str;
    _Local.font = [UIFont boldSystemFontOfSize:25];
    _Local.textColor = [UIColor whiteColor];
    [self.view addSubview:_Local];
    [_Local release];
    
    //您当前所在城市
    self.nowLocation = [[UILabel alloc]init];
    _nowLocation.frame = CGRectMake(self.view.frame.size.width * 1/3 + 20, 10, self.view.frame.size.width * 1/3, self.view.frame.size.height *1/3 *1/5);
    _nowLocation.text = @"[您可能所在城市]";
    _nowLocation.font = [UIFont systemFontOfSize:14];
    _nowLocation.textColor = [UIColor whiteColor];
    [self.view addSubview:_nowLocation];
    [_nowLocation release];
    
    
    //当前温度
    self.temp = [[UILabel alloc]init];
    _temp.frame = CGRectMake(10, self.view.frame.size.height *1/15+10,self.view.frame.size.width *1/3,self.view.frame.size.height * 1 / 12);
    _temp.textColor = [UIColor whiteColor];
    _temp.textAlignment = NSTextAlignmentRight;
    _temp.font = [UIFont boldSystemFontOfSize:60];
    [self.view addSubview:_temp];
    [_temp release];
    
    //当前天气状况(晴)
    self.weatherLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width *1/3 + 10 + self.view.frame.size.width *1/12 - 10, self.view.frame.size.height *1/15+10, self.view.frame.size.width *1/6,self.view.frame.size.height * 1 / 12)];
    _weatherLabel.font = [UIFont boldSystemFontOfSize:20];
    _weatherLabel.textAlignment = NSTextAlignmentCenter;
    _weatherLabel.textColor = [UIColor colorWithRed:204/255.0 green:102/255.0 blue:0/255.0 alpha:1];
    [self.view addSubview:_weatherLabel];
    [_weatherLabel release];
    
    
    //当前天气图片
    self.weatherPhoto = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width * 2/3, 5, self.view.frame.size.width * 1/3, self.view.frame.size.height * 1/5)];
    [self.view addSubview:_weatherPhoto];
    [_weatherPhoto release];
    
    
    //第一张框架底层图
    UIImageView *firstBg=[[UIImageView alloc] initWithFrame:CGRectMake(10, self.view.frame.size.height * 1 / 5 +5, self.view.frame.size.width - 50, self.view.frame.size.height * 1 / 3 - 10)];
    firstBg.image=[UIImage imageNamed:@"boli.png"];
    [self.view addSubview:firstBg];
    [firstBg release];


    //第一张框架面板图
    UIImageView *firstBg1=[[UIImageView alloc] initWithFrame:CGRectMake(10, self.view.frame.size.height * 1 / 5 +5, self.view.frame.size.width - 50, self.view.frame.size.height * 1 / 3 - 10)];
    firstBg1.image=[UIImage imageNamed:@"mianban.png"];
    [self.view addSubview:firstBg1];
    [firstBg1 release];

    //今日
    UILabel *today = [[UILabel alloc]init];
    today.textColor = [UIColor whiteColor];
    today.frame = CGRectMake(15, self.view.frame.size.height * 1 / 5 +5, 100, 40);
    today.font = [UIFont systemFontOfSize:17];
    today.text = @" 今日: ";
    [self.view addSubview:today];
    [today release];
    
    
    //显示最高温度
    UILabel *highest = [[UILabel alloc]init];
    highest.frame = CGRectMake(15, self.view.frame.size.height * 1 / 4 +20 , 100, 50);
    highest.text = @" 最高温度:";
    highest.font = [UIFont systemFontOfSize:17];
    highest.textColor = [UIColor whiteColor];
    [self.view addSubview:highest];
    [highest release];
    
    //获取最高温度
    self.tmax = [[UILabel alloc]init];
    _tmax.frame = CGRectMake(115, self.view.frame.size.height * 1 / 4 +20, 50, 50);
    _tmax.font = [UIFont systemFontOfSize:17];
    _tmax.textColor = [UIColor whiteColor];
    [self.view addSubview:_tmax];
    [_tmax release];
    
    // 白天太阳
    UIImageView *whiteDay = [[UIImageView alloc]initWithFrame:CGRectMake(205, self.view.frame.size.height * 1 / 4 +20, 75, 75)];
    whiteDay.image = [UIImage imageNamed:@"0.png"];
    [self.view addSubview:whiteDay];
    [whiteDay release];
    
    
    //最低温度
    UILabel *lowest = [[UILabel alloc]init];
    lowest.frame = CGRectMake(15, self.view.frame.size.height * 1 / 4 +90 , 100, 50);
    lowest.text = @" 最低温度:";
    lowest.font = [UIFont boldSystemFontOfSize:17];
    lowest.textColor = [UIColor whiteColor];
    [self.view addSubview:lowest];
    [lowest release];
    
    //获取最低温度
    self.tmix = [[UILabel alloc]init];
    _tmix.frame = CGRectMake(120, self.view.frame.size.height * 1 / 4 +90 , 100, 50);
    _tmix.font = [UIFont systemFontOfSize:17];
    _tmix.textColor = [UIColor whiteColor];
    [self.view addSubview:_tmix];
    [_tmix release];
    
    //夜间太阳
    UIImageView *nightDay = [[UIImageView alloc]initWithFrame:CGRectMake(205, self.view.frame.size.height * 1 / 4 +90, 75, 75)];
    nightDay.image = [UIImage imageNamed:@"1.png"];
    [self.view addSubview:nightDay];
    [nightDay release];


    //第二张框架底层图
    UIImageView *secondBg=[[UIImageView alloc] initWithFrame:CGRectMake(10, self.view.frame.size.height * 1 / 5 + self.view.frame.size.height * 1 / 3 + 5, self.view.frame.size.width - 50, self.view.frame.size.height * 1 / 3 - 10)];
    secondBg.image=[UIImage imageNamed:@"boli.png"];
    [self.view addSubview:secondBg];
    [secondBg release];
    
    
    //第二张框架面板图
    UIImageView *secondBg1=[[UIImageView alloc] initWithFrame:CGRectMake(10, self.view.frame.size.height * 1 / 5 + self.view.frame.size.height * 1 / 3 + 5, self.view.frame.size.width - 50, self.view.frame.size.height * 1 / 3 - 10)];
    secondBg1.image=[UIImage imageNamed:@"mianban.png"];
    [self.view addSubview:secondBg1];
    [secondBg1 release];

    
    
    
    //温馨提示
    self.prompt = [[UILabel alloc]init];
    _prompt.frame = CGRectMake(15, self.view.frame.size.height * 1 / 5 + self.view.frame.size.height * 1 / 3 + 5, 100, 40);
    _prompt.text = @" 温馨提示: ";
    _prompt.font = [UIFont systemFontOfSize:17];
    _prompt.numberOfLines = 0;
    _prompt.textColor = [UIColor whiteColor];
    [self.view addSubview:_prompt];

    //提示信息
    self.prompt = [[UILabel alloc]init];
    _prompt.frame = CGRectMake(25, self.view.frame.size.height * 2/3, 250, 50);
    _prompt.font = [UIFont boldSystemFontOfSize:17];
    _prompt.numberOfLines = 0;
    _prompt.textColor = [UIColor orangeColor];
    [self.view addSubview:_prompt];
    
    
    
    
    
}

//所有赋值数据
- (void)freshData{
    self.Local.text = self.str;
    self.temp.text = self.weather.treal;
    self.tmax.text = self.weather.tmax;
    self.tmix.text = self.weather.tmin;
    
    if ([self.weather.weather_day isEqualToString:@"qing"]) {
        self.weatherPhoto.image = [UIImage imageNamed:@"0.png"];
        self.weatherLabel.text = @"晴";
        self.prompt.text = @"今日天气不错,多出去走走吧~";
     
    }
    else if ([self.weather.weather_day isEqualToString:@"yin"]){
        self.weatherPhoto.image = [UIImage imageNamed:@"2.png"];
        self.weatherLabel.text = @"阴";
        self.prompt.text = @"今日天气有些阴暗,不要影响您的心情~";

    }
    else if ([self.weather.weather_day isEqualToString:@"大雾"]){
        self.weatherPhoto.image = [UIImage imageNamed:@"31.png"];
        self.weatherLabel.text = @"雾";
        self.prompt.text = @"出门请带好口罩,防雾霾~";

        
    }
    else if ([self.weather.weather_day isEqualToString:@"xiaoyu"]){
        self.weatherPhoto.image = [UIImage imageNamed:@"7.png"];
        self.weatherLabel.text = @"小雨";
        self.prompt.text = @"今日会有小雨降临,出门请带好雨具!";

        
    }
    else if ([self.weather.weather_day isEqualToString:@"dayu"]){
        self.weatherPhoto.image = [UIImage imageNamed:@"8.png"];
        self.weatherLabel.text = @"大雨";
        self.prompt.text = @"今日会有大雨降临,出门请带好雨具! 出门慢行, 小心路滑!";

        
    }
    else if ([self.weather.weather_day isEqualToString:@"暴雨"]){
        self.weatherPhoto.image = [UIImage imageNamed:@"12.png"];
        self.weatherLabel.text = @"暴雨";
        self.prompt.text = @"今日会有暴雨降临,出门请带好雨具! 出门慢行, 小心路滑!";

        
    }
    else if ([self.weather.weather_day isEqualToString:@"xiaoxue"]){
        self.weatherPhoto.image = [UIImage imageNamed:@"14.png"];
        self.weatherLabel.text = @"小雪";
        self.prompt.text = @"今日会有小雪,出门慢行, 小心路滑, 注意保暖~";

    }
    else if ([self.weather.weather_day isEqualToString:@"daxue"]){
        self.weatherPhoto.image = [UIImage imageNamed:@"31.png"];
        self.weatherLabel.text = @"大雪";
        self.prompt.text = @"今日会有大雪,出门慢行, 小心路滑, 注意保暖~";

    }
    else if ([self.weather.weather_day isEqualToString:@"leiyu"]){
        self.weatherPhoto.image = [UIImage imageNamed:@"4.png"];
        self.weatherLabel.text = @"雷雨";
        self.prompt.text = @"今日是雷雨天气,出门请带好雨具! 出门慢行, 小心路滑!";

        
    }
    else if ([self.weather.weather_day isEqualToString:@"duoyun"]){
        self.weatherPhoto.image = [UIImage imageNamed:@"2.png"];
        self.weatherLabel.text = @"多云";
        self.prompt.text = @"今日天气有些阴暗,不要影响您的心情~";

    }
    else if ([self.weather.weather_day isEqualToString:@"yujiaxue"]){
        self.weatherPhoto.image = [UIImage imageNamed:@"6.jpg"];
        self.weatherLabel.text = @"雨夹雪";
        self.prompt.text = @"今日有雨夹雪,记得带好雨具,出门慢行, 小心路滑, 注意保暖~";

        
    }
    else if ([self.weather.weather_day isEqualToString:@"baoxue"]){
        self.weatherPhoto.image = [UIImage imageNamed:@"28.png"];
        self.weatherLabel.text = @"暴雪";
        self.prompt.text = @"今日会有暴雪降临,出门慢行, 小心路滑!注意保暖~";

    }
    else {
        self.weatherPhoto.image = [UIImage imageNamed:@"0.png"];
        self.weatherLabel.text = @"晴天";
        self.prompt.text = @"今日天气不错,多出去走走吧,但要注意保暖哦~";

    }


}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
